﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

namespace Nirvana
{
    [RequireComponent(typeof(RawImage))]
    [AddComponentMenu("Nirvana/UI/Language/RawImage I18N")]
    [DisallowMultipleComponent]
    [ExecuteInEditMode]
    public sealed class RawImageI18N : Translatable
    {
        [Serializable]
        private struct BindLanguageImage
        {
            [Tooltip("The languaget type.")]
            public I18NLanguageType languagetype;
            [Tooltip("The translate Texture.")]
            public Texture translate;
        };

        /// <summary>
        /// 内置翻译表，不通过keyid获取，直接设置
        /// </summary>
        [SerializeField]
        [Tooltip("The bind Language Image list.")]
        private List<BindLanguageImage> binds = new List<BindLanguageImage>();

        protected override void TranslateText()
        {
            RawImage img = this.GetComponent<RawImage>();
            if (img == null)
            {
                return;
            }

            this.UpdateText(img);
        }

        public  void GetTranslate(out Texture img)
        {
            img = null;
            if (!string.IsNullOrEmpty(KeyId))
            {
                
            }
            else
            {
                I18NLanguageType language = I18N.Language;
                foreach (var f in binds)
                {
                    if (f.languagetype == language)
                    {
                        img = f.translate;
                        return;
                    }
                }
            }

        }

        private void UpdateText(RawImage img)
        {
            if (Application.isPlaying)
            {
                Texture msg;
                GetTranslate(out msg);
                if(msg!=null)
                img.texture = msg;
            }
            else
            {

#if UNITY_EDITOR
                Texture msg;
                GetTranslate(out msg);
                if(msg != null)
                {
                    if (img.texture == null)
                    {
                        img.texture = msg;
                        EditorUtility.SetDirty(img);

                    }
                    else if (msg.name != img.texture.name)
                    {
                        img.texture = msg;
                        EditorUtility.SetDirty(img);
                    }
                }

#endif
            }

        }

    }
}

